
var app = require('../../server/server');
module.exports = function(Monitor) {

	Monitor.getNearlyTen = function (lat, lng, cb) {
    var option = {
      where: {
        and: [
          {JD: {between: [lng - 0.01, lng + 0.01]}},
          {WD: {between: [lat - 0.01, lat + 0.01]}}
        ]
      }
    };
    var result = [];
    Monitor.find(option, function (err, data) {
      for(var i = 0; i < data.length; i++) {
        var bdjwd = app.models.util.bd_encrypt(data[i].WD - 0, data[i].JD - 0);
        result.push({
          type: 'monitor',
          msg: data[i].MC,
          addr: data[i].PCS,
          lat: bdjwd[0],
          lng: bdjwd[1],
          // lat: data[i].LATITUDE - 0,
          // lng: data[i].LONGITUDE - 0,
          distance: Math.floor(Math.abs(bdjwd[0] - lat) * 110000 
            + Math.abs(bdjwd[1] - lng) * 94000)
        })
      }
      cb(null, result);
    })
  };

  Monitor.remoteMethod(
    'getNearlyTen', {
      http: {path: '/getNearlyTen', verb: 'post'},
      accepts: [
        {arg: 'lat', type: 'number', required: 'true'},
        {arg: 'lng', type: 'number', required: 'true'}
      ],
      returns: {type: 'array', root: true}
    }
  );

  Monitor.searchData = function (searchText, lat, lng, cb) {
    var option = {
      where: {
        and: [
          {MC: {like: '%' + searchText + '%'}}
        ]
      }
    };
    var result = [];
    Monitor.find(option, function (err, data) {
      for(var i = 0; i < data.length; i++) {
        var bdjwd = app.models.util.bd_encrypt(data[i].WD - 0, data[i].JD - 0);
        result.push({
          type: 'monitor',
          msg: data[i].MC,
          addr: data[i].PCS,
          lat: bdjwd[0],
          lng: bdjwd[1],
          distance: Math.floor(Math.abs(bdjwd[0] - lat) * 110000 
            + Math.abs(bdjwd[1] - lng) * 94000)
        })
      }
      cb(null, result);
    })
  };

  Monitor.remoteMethod(
    'searchData', {
      http: {path: '/searchData', verb: 'post'},
      accepts: [
        {arg: 'searchText', type: 'string', required: 'true'},
        {arg: 'lat', type: 'number', required: 'true'},
        {arg: 'lng', type: 'number', required: 'true'}
      ],
      returns: {type: 'array', root: true}
    }
  );

};
